/**
 * 历史图片
 */
$(function(){
	HistoryPic.init();
	
	/*$("#chosecar").click(function(){
		$("#chosecar").attr("style","background: #1d63a9;")
		$("#choseenterpirse").attr("style","background: #dfdfdf");
		$("#enterpriseSelDiv").hide();	
		$("#vehicleSelDiv").show();
	});
	$("#choseenterpirse").click(function(){		
		$("#choseenterpirse").attr("style","background: #1d63a9;")
		$("#chosecar").attr("style","background: #dfdfdf");
		$("#vehicleSelDiv").hide();
		$("#enterpriseSelDiv").show();	
	})*/
});

var HistoryPic = {
		init : function(){
			var me = this;
			me.initEvent();
			me.initEmptyVehicleList();
			me.initVehicleEnterpriseList()
			me.initQueryTime();
			me.picCharts = this.initCharts();
			me.queryChartData();
			me.pic();
			MapTool.init();
		},
		initEvent: function(){
			var me = this;
			
			$("#chooseObj").on('change',function(){
				var chose = $("#chooseObj").val();
				if (chose == "1") {  //"1"代表的是企业 2代表的是司机
					//me.queryChose="enterprise";
					$("#enterpriseSelDiv").show();
					$("#vehicleSelDiv").hide();
				}else if (chose == "2") {
				//	me.queryChose="driver";
					$("#enterpriseSelDiv").hide();
					$("#vehicleSelDiv").show();
				}
			});
			$("#chooseObj").select2();
			
			$("#queryBtn").click(function(){
				var startTime=$("#inputStartDate").val();
			   	var endTime=$("#inputEndDate").val();
			   	var vehicle=$.trim($("#selectVehicleSel").val());
			   	var enterprise=$("#selectVehicleEnterpriseSel").val();
			   	var startTimeSub = startTime.substr(0 ,7);
			   	var endTimeTimeSub = endTime.substr(0 ,7);
			   	if(startTimeSub!=endTimeTimeSub){
			   		global.ajaxLoading.pop("不能跨月查询", true, 2000);
			   		return;
			   	}
				var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
		    	var end_date = new Date(end_str);//将字符串转化为时间  
		    	//开始时间  
		    	var sta_str = (startTime).replace(/-/g,"/");  
		    	var sta_date = new Date(sta_str); 
		    	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
		    	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
		    	if(days>7){
		    		global.ajaxLoading.pop("查询时间不能超过7天",false,2000);
		    		return;
		    	}
			   	/*if(vehicle!=null&&vehicle!="" &&enterprise!=null&&enterprise!=""){
			   		return;
			   	}*/
			   	global.ajaxLoading.pop('正在拼命加载,请稍候!',true);
				me.queryChartData(startTime,endTime);
				
	    	});
		},
	    initEmptyVehicleList: function(){
	    	$("#selectVehicleSel").select2({
		        theme: "default",
		        allowClear: true,
		        placeholder: "全部车辆",
		        ajax:{
		            url:appCtx + "/system/common/selectVehicle.html",
		            dataType:"json",
		            delay:250,
		            data:function(params){
		                return {
		                    name: params.term,
		                    page: params.page || 1
		                };
		            },
		            cache:true,
		            processResults: function (res, params) {
				    	if(res){
				    		var options = [];
				    		var option = {"id":" ", "text":"全部车辆"};
				    		options.push(option);
		    				$.each(res,function(index,obj) {
		    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
	    	                    options.push(option);
		    				});
	    	                return {
	    	                	results: options,
	    	                    pagination: {
	    	                        more:false
	    	                    }
	    	                };
				    	}
		            },
		            escapeMarkup: function (markup) { return markup; },
		            minimumInputLength: 1
		        }
		    });
//	    	$.ajax({
//	    		type : 'post',
//	    		async : true,
//	    		url : appCtx + "/report/historyPic/queryVehicleList.html",
//	    		cache : false,
//	    		dataType : "JSON",
//	    		success : function(data) {			
//	    			if(data){
//	    				$('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
//	    				var selectStr="";
//	    				selectStr+="<option value=''>请选择车辆</option>";
//	    				for(var i=0;i<data.length;i++){
//	    					selectStr+="<option value='"+data[i].vehicle_no+"'>"+data[i].vehicle_no+"</option>";
//	    				}
//	    				
//	    				$('#selectVehicleSel').html(selectStr);
//	    				
//	    				$("#selectVehicleSel").select2();
//
//	    			}
//	    		}
//	    	});
	    },
	    initVehicleEnterpriseList:function(){
	    	$('#selectVehicleEnterpriseSel').select2({
	    		theme: "default",
	 	        allowClear: true,
	 	        placeholder: "全部业户",
	 	        ajax:{
	 	            url:appCtx + "/system/common/queryEnterprise.html",
	 	            dataType:"json",
	 	            delay:250,
	 	           async : true,
	 	            data:function(params){
	 	                return {
	 	                    name: params.term,
	 	                    page: params.page || 1
	 	                };
	 	            },
	 	            cache:true,
	 	            processResults: function (res, params) {
	 			    	if(res){
	 			    		var options = [];
	 			    		var option = {"id":" ", "text":"全部业户"};
	 			    		options.push(option);
	 	    				$.each(res,function(index,obj) {
	 	    					var option = {"id":obj.id, "text":obj.text};
	     	                    options.push(option);
	 	    				});
	     	                return {
	     	                	results: options,
	     	                    pagination: {
	     	                        more:false
	     	                    }
	     	                };
	 			    	}
	 	            },
	 	            escapeMarkup: function (markup) { return markup; },
	 	            minimumInputLength: 1
	 	        }
	    	})
	    	
	    	/*var me = this;
	    	$.ajax({
	    		type : 'post',
	    		async : true,
	    		url : appCtx + "/system/common/queryEnterprise.html",
	    		cache : false,
	    		dataType : "JSON",
	    		success : function(data) {			
	    			if(data){
	    				var selectStr="<option value=''>请选择业户</option>";
	    				for(var i=0;i<data.length;i++){
	    					selectStr+="<option value='"+data[i].ID+"'>"+data[i].text+"</option>";
	    				}
	    				$('#selectVehicleEnterpriseSel').html(selectStr);		
	    				$("#selectVehicleEnterpriseSel").select2();
	    			}
	    		}
	    	});*/
	    },
		initCharts : function(){
			var me = this;
			var option = {
					color: ['#3398DB'],
				    tooltip : {
				        trigger: 'axis',
				        show: true,
				        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
				        	show: false,
				            type : 'line'        // 默认为直线，可选为：'line' | 'shadow'
				        },
				        formatter:function(a){
				        	if(a[0].name==''){
				        		return;
				        	}
				        	var relVal = "";
				        	relVal = a[0].name+"："+a[0].value+"张";
				        	return relVal;
				        }
				    },
				    grid: {
				        left: '3%',
				        right: '4%',
				        containLabel: true
				    },
				    xAxis : [
				        {
				            type : 'category',
				            data : [],//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
				            axisTick: {
				                alignWithLabel: true
				            },
				            axisLabel:{
				            	
				            	textStyle: {
		                            fontSize: 10
		                        }
				            }
				        }
				    ],
				    yAxis : [
				        {
				            type : 'value',
				            min: 0,
					    	minInterval: 1,
					    	axisLabel: {
			                      formatter: function (value, index) {
			                    	  if (value >= 1 || value == 0) {
			                            	if (value%1 === 0) {
			                            		return value;
			                            	}
			                            }
			                        }
			                 },
				        }
				    ],
				    series : [
				        {
				            name:'',
				            type:'bar',
				            barMaxWidth: '40px',
				            itemStyle: {
				            	 label : {
				                        show: true, position: 'insideTop' //柱状图顶部显示数字
				                }
				            },
				            data:[],//[10, 52, 200, 334, 390, 330, 220]
				        }
				    ],
				    dataZoom: [{
				        type: 'inside',
				        start: 0,
				        end: 100
				    }, {
				        start: 0,
				        end: 100,
				        fillerColor:'#A3E1A3',
				        handleColor:'#83A7D1'
				    }]
			};
	        
	        var myChart = echarts.init(document.getElementById('myCharts'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            
            if (option.series[0].data.length == 0) {
            	$('.carousel-control').hide();
            }
            else {
            	$('.carousel-control').show();
            }
            
            myChart.on('click', function(param){
            	global.ajaxLoading.pop('正在拼命加载,请稍候!',true);
            	var xAxisData = me.xAxisData;
            	var vehicleNo = xAxisData[param.dataIndex];
            	me.queryPicListByVehicleNo(vehicleNo);
            });
            
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	picChartDom : myChart
            };
	        
		},
		queryChartData: function(){
			var me = this;
			var startTime=$("#inputStartDate").val();
			var endTime=$("#inputEndDate").val();
			var vehicleNo=$.trim($("#selectVehicleSel").val());
			var enterprisseId=$('#selectVehicleEnterpriseSel').val();
			$.ajax({
				type : 'post',
				async : true,
				url : appCtx+"/report/historyPic/queryChartData.html",
				data :{
					vehicleNo:vehicleNo,
					startTime:startTime,
					endTime:endTime,
					enterprisseId:enterprisseId
				},
				cache : false,
				dataType : "JSON",
				success : function(data) {
					if(data&&data.xAxisData&&data.xAxisData.length>0){
						var option = me.picCharts.option;
						option.xAxis[0].data = data.xAxisData;//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
						option.series[0].data = data.series;//[10, 52, 200, 334, 390, 330, 220];
						me.picCharts.refash(option);
						me.xAxisData = data.xAxisData;
						me.startTime = startTime;
						me.endTime = endTime;
						me.queryPicListByVehicleNo(data.xAxisData[0]);
					}else{
						var option = me.picCharts.option;
						option.xAxis[0].data = [];//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
						option.series[0].data = [];//[10, 52, 200, 334, 390, 330, 220];
						me.picCharts.refash(option);
						me.queryPicListByVehicleNo([]);
						global.ajaxLoading.pop('未查询到数据!',false,2000);
					}
				}
			});
		},
		queryPicListByVehicleNo: function(vehicleNo){
			var me = this;
			var startTime=me.startTime + " 00:00:00";
			var endTime=me.endTime + " 23:59:59";
			$.ajax({
				type : 'post',
				/*async : true,*/
				url : appCtx+"/report/historyPic/queryPicListByVehicleNo.html",
				data :{
					vehicleNo:vehicleNo,
					startTime:startTime,
					endTime:endTime
				},
				cache : false,
				dataType : "JSON",
				success : function(data) {
					if(data){
						me.initPicListHtml(data);
					}else{
						$('.carousel-inner').html('');
					}			
					global.ajaxLoading.close();
				}
			});
		},
		initPicListHtml: function(list){
			var me = this;
			me.picList = null;
			$('.carousel-inner').html('');
			var html = '';
			for(var i=0;i<list.length;i++){
				if(i%6==0){
					if(i==0){
						html+='<div class="active item">';
					}else{
						html+='</ul>';
						html+='</div>';
						html+='<div class="item">';
					}
					html+='<ul class="row-fluid ">';					
				}
				html+='<li class="span2"><a class="db imgA largeImg" href="javascript:void(0);" index="'+i+'" vehicleId="'+list[i].vehicle_id+'"  imgSrc='+list[i].imgUrl+'><img src="'+list[i].imgUrl+'"></a></li>';
			}
			me.picList = list;
			$('.carousel-inner').html(html);
			if(list.length<=6){
				$('.carousel-control').hide();
			}else{
				$('.carousel-control').show();
			}
		},
	    initQueryTime:function(){//默认时间
	        var todayDate = new Date();
	        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
	        	
	        var beforeDate = new Date(); //前一天
		    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
		    if (mm.length == 1) {
		        mm = '0' + mm;
		    }
		    if (dd.length == 1) {
		        dd = '0' + dd;
		    }
	        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
	        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
	      },
		/**
		 * 图片切换
		 */
		pic : function(){
			var me = this;
				var arr = [0];
				var index = 0;
				var length = 0;
				//$('#myCarousel').rebox({ selector: '.imgA' });
				$('#myCarousel').on('slide.bs.carousel', function (event) {
					var $hoder = $('#myCarousel').find('.item'),
			          $items = $(event.relatedTarget);
		        	//getIndex就是轮播到当前位置的索引
		        	var getIndex= $hoder.index($items);
		        	if(arr.indexOf(getIndex) == -1){
		        		arr.push(getIndex);
		        		//加载图片
		        	}
				});
				
				$('#myCarousel').on('click','.imgA',function(e){
					e.preventDefault();
					//var picIndex= JSON.parse($(this).attr('index'));
					index = JSON.parse($(this).attr('index'));
					length = $('#myCarousel').find('.imgA').length;
					var picObj= me.picList[index];
					var src = picObj.imgUrl;
					$('#largeImgage').attr('src',src);
					$('.largeImgPop,#mask').show();
					$('.pageSize.pa').html(index+1+'/'+length);
					if(length==1){
						$('.prevNext').hide();
					}else{
						$('.prevNext').show();
					}
					//地图信息
					MapTool.loadMapData(picObj);

				});
				
				$('.largeImgPop').find('.close').click(function(){
					$('.largeImgPop,#mask').hide();
					$('#largeImgage').attr('src','');
				});
				
				
				$('.largeImgPop').find('.prev').click(function(){
					if(index===0){
						index = length-1;
					}else{
						index--;
					}
					var src = $('#myCarousel').find('.imgA').eq(index).attr('imgSrc');
					$('#largeImgage').attr('src',src);
					var picObj= me.picList[index];
					MapTool.loadMapData(picObj);
					$('.pageSize.pa').html(index+1+'/'+length);
				});
				
				$('.largeImgPop').find('.next').click(function(){
					if(index===length-1){
						index = 0;
					}else{
						index++;
					}
					var src = $('#myCarousel').find('.imgA').eq(index).attr('imgSrc');
					$('#largeImgage').attr('src',src);
					var picObj= me.picList[index];
					MapTool.loadMapData(picObj);
					$('.pageSize.pa').html(index+1 +'/'+length);
				});
			},	   
};

var MapTool = {
		init: function(){
			var me = this;
			me.oldVehicleId = 0;
			me.map = me.map();
		},
		 /**
		    * 地图渲染
		    * */
		map: function(){
			var me = this;
		     var map = new AMap.Map('mymap',{
		         resizeEnable: true,
		         zoom: 14,
		         center: [113.645096,23.631439]
		      });
		      return map;
		},
		/**
	      * 增加覆盖物
	      * @param map
	      * @param lon
	      * @param lat
	      */
		 addMarker : function(data){
			 var me = this;
			marker = new AMap.Marker({
		        map: me.map,
		        position: [data.gdLng,data.gdLat],
		        icon: global.url.domain + "gps-web/resources/images/mapTool/car1.png",
		        offset: new AMap.Pixel(-15, -10),
		        autoRotation: true
		    });
			
			this.initHashMap.GlobalMarkerCache.put(data.vehicle_id,marker);
		},
		
		addInfoMarker : function(data){
			var me = this;
			var status=data.status? "定位" : "盲区";
			
			var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -20)}); 
			MapTool.infoWindow = infoWindow;
			marker = new AMap.Marker({
			    map: me.map,
			    position: [data.gdLng,data.gdLat],
			    icon: global.url.domain + "gps-web/resources/images/mapTool/car1.png",
			    offset: new AMap.Pixel(-15, -10),
			    autoRotation: true
			});
			marker.content = '车牌：'+data.vehicle_no+'</br>拍照时间：'+data.gpsTime+'</br>车速：'+data.gpsSpeed+' 公里/小时</br>里程: '+data.gpsMileage+' 公里</br>状态：'+status+'<br/>'+'拍照地点：<span id="address" name="address"></span>';
			marker.on('click', function(e){
				infoWindow.setContent(e.target.content+me.address);
				infoWindow.open(me.map, e.target.getPosition());
			});
			this.initHashMap.GlobalMarkerCache.put(data.vehicle_id,marker);
			
			infoWindow.setContent(marker.content);
			infoWindow.open(me.map, marker.getPosition());
			MapTool.getAddress(data);
		},
		/**
		 * 设置地图中心点
		 * @param data  定位数据
		 */
		setCenter : function(data){
			var me = this;
			me.map.setZoomAndCenter(14, new AMap.LngLat(data.gdLng,data.gdLat));
		},
		/**
		 * 高德逆地址解析
		 * @param ctrl  地址标签ID
		 * @param  data 定位经纬度
		 */
		getAddress : function(data){
			var me = this;
			var geocoder = new AMap.Geocoder({
				radius: 1000,
				extensions: "all"
		    });        
			geocoder.getAddress(new AMap.LngLat(data.gdLng, data.gdLat), function(status, result) {
				if (status === 'complete' && result.info === 'OK') {
					var address=result.regeocode.formattedAddress;
					me.initHashMap.GlobalAddressCache.put(data.longitude+'_'+data.longitude,address);
					me.address = address;
					$("#address").html(address);
				}
			});     
			    
		},
	    /*初始化各类数据，用于存储*/
	    initHashMap : {
	        GlobalMarkerCache : new HashMap(),      // 地图车辆缓存  key: Id value:marke
	        GlobalAddressCache : new HashMap()
	    },
		/**
		 * 删除覆盖物
		 * @param vid 车辆ID
		 */
		clearMarker : function(vid){
			var me = this;
			var marker = me.initHashMap.GlobalMarkerCache.get(vid);
			 if(marker){
				 var infoWindow = MapTool.infoWindow;
				 infoWindow.close();
		         marker.setMap(null);
		         marker = null;
		     }
		},
		loadMapData: function(picObj){
			var data = {
					longitude: picObj.coordinates.coordinates[0],
					latitude: picObj.coordinates.coordinates[1],
					gdLng: picObj.gdLng,
					gdLat: picObj.gdLat,
					vehicle_id: picObj.vehicle_id,
					vehicle_no: picObj.vehicle_no,
					gpsSpeed: picObj.gps_speed,
					gpsMileage: picObj.mileage,
					gpsTime: picObj.gpsTimeStr,
					address: picObj.address,
					status: picObj.status
				};
			MapTool.setCenter(data);
			MapTool.clearMarker(MapTool.oldVehicleId);
			MapTool.getAddress(data);
			MapTool.addInfoMarker(data);
			MapTool.oldVehicleId = picObj.vehicle_id;
		}
};
